package fortunetelling.fortunetelling.listener;

import fortunetelling.fortunetelling.FortuneTelling;
import fortunetelling.fortunetelling.bean.Fortune;
import fortunetelling.fortunetelling.utils.FortuneConvertUtils;
import org.bukkit.Material;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerFishEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;

/**
 * @ClassName: Event
 * @Date: 2020/10/5 0005 20:05
 * @Description:
 */
public class FishingEventListener implements Listener {
    @EventHandler
    public void fishing(PlayerFishEvent playerFishEvent) {
        PlayerFishEvent.State state = playerFishEvent.getState();
        Player player = playerFishEvent.getPlayer();
        if (state.equals(PlayerFishEvent.State.CAUGHT_FISH)
                || state.equals(PlayerFishEvent.State.CAUGHT_ENTITY)) {
            if (playerFishEvent.getCaught() != null) {
                Fortune fortune = FortuneTelling.FORTUNE_TELLING_MAP.get(player.getName());
                if (fortune != null) {
                    String fortuneName = fortune.getName();
                    int i = FortuneConvertUtils.probabilityCalculation(fortuneName);
                    Entity caught = playerFishEvent.getCaught();
                    if (caught == null) {
                        return;
                    }
                    if (i > 0) {
                        PlayerInventory inventory = player.getInventory();
                        Material material = Material.matchMaterial(caught.getName());
                        if (material != null) {
                            player.sendMessage("§a由于您的运势为：" + fortuneName + "！ 您额外获得了一个" + caught.getName());
                            inventory.addItem(new ItemStack(material, 1));
                        }
                    } else if (i < 0) {
                        player.sendMessage("§4由于您的运势为：" + fortuneName + "！ 您失去了" + caught.getName());
                        caught.remove();
                    }
                }
            }
        }
    }
}
